import { defineStore } from 'pinia';
import { fetchMe, getCurrentUser } from '@/api/user';

export interface IUserState {
  token: string;
  expire_in: number;
  username: string;
  avatar: string;
  permissions: [];
  // 新增完整用户信息字段
  id: number | null;
  name: string;
  phone: string;
  gender: string;
  role: string;
  extra_info: string;
  is_active: boolean;
  create_time: string;
}

// 常量定义
const ROLES = [
  { title: 'Admin', value: 'admin' },
  { title: 'Author', value: 'author' },
  { title: 'Editor', value: 'editor' },
  { title: 'Maintainer', value: 'maintainer' },
  { title: 'Subscriber', value: 'subscriber' }
];

const STATUS_OPTIONS = [
  { title: 'Pending', value: 'pending' },
  { title: 'Active', value: 'active' },
  { title: 'Inactive', value: 'inactive' }
];

/** User Store */
export const useUserStore = defineStore('user', {
  // Default Config State
  state: (): IUserState => ({
    token: '',
    expire_in: 0,
    username: '',
    avatar: '',
    permissions: [],
    // 新增字段
    id: null,
    name: '',
    phone: '',
    gender: '',
    role: '',
    extra_info: '',
    is_active: true,
    create_time: ''
  }),
  // Getters
  getters: {
    getRoles() {
      return ROLES;
    },
    getUsername(state) {
      return state.username;
    },
    getStatusOptions() {
      return STATUS_OPTIONS;
    },
    getAccessToken(state) {
      return state.token;
    },
    // 新增getters
    getCurrentUser(state) {
      return {
        id: state.id,
        username: state.username,
        name: state.name,
        phone: state.phone,
        gender: state.gender,
        role: state.role,
        extra_info: state.extra_info,
        is_active: state.is_active,
        create_time: state.create_time,
        avatar: state.avatar
      };
    },
    getRoleText(state) {
      const roleMap: Record<string, string> = {
        STUDENT: '学生',
        INITIAL_VISITOR: '初访员',
        ASSISTANT: '心理助理',
        CONSULTANT: '咨询师',
        ADMIN: '管理员'
      };
      return roleMap[state.role] || state.role;
    },
    getGenderText(state) {
      return state.gender === 'M' ? '男' : '女';
    },
    getExtraInfo(state) {
      try {
        return state.extra_info ? JSON.parse(state.extra_info) : {};
      } catch {
        return {};
      }
    }
  },
  // Actions
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setUsername(username: string) {
      this.username = username;
    },
    setProfile(profile: any) {
      this.username = profile.username;
      this.avatar = profile.avatar;
    },
    // 新增：设置完整用户信息
    setUserInfo(userInfo: any) {
      this.id = userInfo.id;
      this.username = userInfo.username;
      this.name = userInfo.name;
      this.phone = userInfo.phone;
      this.gender = userInfo.gender;
      this.role = userInfo.role;
      this.extra_info = userInfo.extra_info;
      this.is_active = userInfo.is_active;
      this.create_time = userInfo.create_time;
      
      // 解析额外信息中的头像
      try {
        const extraInfo = userInfo.extra_info ? JSON.parse(userInfo.extra_info) : {};
        this.avatar = extraInfo.avatar || '';
      } catch {
        this.avatar = '';
      }
    },
    // 新增：获取当前用户完整信息
    async getCurrentUserInfo(): Promise<boolean> {
      if (!this.username) {
        return Promise.reject(false);
      }
      
      try {
        const response = await getCurrentUser(this.username);
        if (response.data && response.data.success) {
          this.setUserInfo(response.data.data);
          return Promise.resolve(true);
        }
        return Promise.reject(false);
      } catch (e) {
        return Promise.reject(false);
      }
    },
    async getProfile(): Promise<boolean> {
      try {
        const { data } = await fetchMe();
        // set user profile
        this.setProfile(data);
        return Promise.resolve(true);
      } catch (e) {
        return Promise.reject(false);
      }
    },
    // 新增：清空用户信息
    clearUserInfo() {
      this.token = '';
      this.username = '';
      this.name = '';
      this.phone = '';
      this.gender = '';
      this.role = '';
      this.extra_info = '';
      this.avatar = '';
      this.id = null;
      this.is_active = true;
      this.create_time = '';
    }
  },
  // Data persistence destination
  persist: {
    key: import.meta.env.VITE_APP_WEBSTORAGE_NAMESPACE ?? 'vuetify',
    storage: window.sessionStorage
  }
});
